<!--  -->
<template>
  <a-modal
    width="1000px"
    :visible="visible"
    :keyboard="false"
    @ok="submit"
    @cancel="cancel"
    title="年度产值"
  >
    <template slot="footer">
      <a-button
        key="back"
        @click="cancel"
      >取 消</a-button>

        <a-button v-if="yearDialogType == 'edit'"
          key="submit"
          type="primary"
          :loading="loading" @click="submit"
        >确 定</a-button>
    </template>
    <a-spin :spinning="spinning">
      <a-form-model
        :model="form"
        :label-col="labelCol"
        :wrapper-col="wrapperCol"
      >
        <a-row>
          <a-col :span="12">
            <a-form-model-item
              label="年份"
              class="custom-width"
            >
              <a-input
                v-model="form.year"
                :disabled="true"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="全年产值指标(万元)">
              <a-input
                v-model="form.yearPlanOutput"
                :disabled="true"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item
              label="记录人"
              class="custom-width"
            >
              <a-input
                v-model="form.recorderName"
                :disabled="true"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="记录时间">
              <a-input
                v-model="form.recorderTime"
                :disabled="true"
              />
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
      <a-row>
        <a-col
          :span="24"
          style="margin-bottom: 10px; color: rgba(0, 0, 0, 0.85)"
        >月度产值指标</a-col>
        <a-col :span="24">
          <a-table
            bordered
            :data-source="dataSource"
            :columns="columns"
            :pagination="false"
          >
            <template
              slot="outputValue1"
              slot-scope="text, record"
            >
              <editable-cell
                v-bind="$props"
                :text="record['outputValue1']"
                :nullValue="record.id1?true:false"
                @change="onCellChange(record.key, 'outputValue1', $event)"
              />
            </template>
            <template
              slot="outputValue2"
              slot-scope="text, record"
            >
              <editable-cell
                v-bind="$props"
                :text="record['outputValue2']"
                :nullValue="record.id2?true:false"
                @change="onCellChange(record.key, 'outputValue2', $event)"
              />
            </template>
            <template
              slot="outputValue3"
              slot-scope="text, record"
            >
              <editable-cell
                v-bind="$props"
                :text="record['outputValue3']"
                :nullValue="record.id3?true:false"
                @change="onCellChange(record.key, 'outputValue3', $event)"
              />
            </template>
          </a-table>
        </a-col>
      </a-row>
    </a-spin>
    <!-- 选择审批人 -->
    <selectApprover
      :business-id="businessId"
      :process-config="setProcessConfig"
      :is-close-upper="false"
      @close="cancel"
    />
    <!-- 选择审批人 -->
  </a-modal>
</template>

<script>
import EditableCell from './EditableCell'
import { getOutputYearDetail, getOutputYearInputYear } from '@/api/project/productionRecords'
export default {
  name: 'YearDialog',
  props: ['visibleDialog', 'yearId', 'isDetails', 'yearDialogType',],
  data() {
    return {
      labelCol: { span: 4 },
      wrapperCol: { span: 14 },
      visible: false,
      loading: false,
      form: {},
      dataSource: [],
      columns: [
        {
          title: '月份',
          dataIndex: 'month1',
          width: '80px'
        },
        {
          title: '当月计划产值(万元)',
          index: 1,
          scopedSlots: { customRender: 'outputValue1' }
        },
        {
          title: '月份',
          dataIndex: 'month2',
          width: '80px'
        },
        {
          title: '当月计划产值(万元)',
          index: 2,
          scopedSlots: { customRender: 'outputValue2' }
        },
        {
          title: '月份',
          dataIndex: 'month3',
          width: '80px'
        },
        {
          title: '当月计划产值(万元)',
          index: 3,
          scopedSlots: { customRender: 'outputValue3' }
        }
      ],
      spinning: false,
      monthVOListData:[],
      // 流程配置
      processConfig: null,
      //点击提交发送流程配置值
      setProcessConfig: null,
      // 业务id
      businessId: null
    }
  },

  components: { EditableCell },

  computed: {},

  async created() {
    //获取通过获取流程配置值
    this.processConfig = await this.$getConfigFn('project_year_output_value')
  },

  watch: {
    visibleDialog(val) {
      if (val) {
        this.visible = val
        this.getOutputYearDetail()
      }
    },
    dataSource: {
      handler(val) {
        if (this.yearDialogType == 'edit') {
          let num = 0
          val.map((v) => {
            if (v.outputValue1 ?? '' !== '') {
              num += v.outputValue1 * 100
            }
            if (v.outputValue2 ?? '' !== '') {
              num += v.outputValue2 * 100
            }
            if (v.outputValue3 ?? '' !== '') {
              num += v.outputValue3 * 100
            }
          })
          this.form.yearPlanOutput = (num / 100).toFixed(2)
        }
      },
      deep: true
    }
  },

  mounted() {},

  methods: {
    cancel() {
      this.form = {}
      this.dataSource = []
      this.$emit('refreshYearList')
      this.$emit('update:visibleDialog', false)
      this.visible = false
    },
    // 针对下发的月份 重新整理
    handlerMonth(monthVOList) {
      const tempList = [
        ['1月', '2月', '3月'],
        ['4月', '5月', '6月'],
        ['7月', '8月', '9月'],
        ['10月', '11月', '12月']
      ]
      const dataSource = tempList.map((v, vi) => {
        const obj = {
          key: vi,
          month1: '',
          month2: '',
          month3: '',
          id1: '',
          id2: '',
          id3: '',
          outputValue1: '',
          outputValue2: '',
          outputValue3: ''
        }
        // v === ['1月', '2月', '3月'],
        v.map((i, ii) => {
          const findData = monthVOList.filter((m) => m.monthly == i)
          if(findData[0]){ //有值
            obj[`id${ii + 1}`] = findData[0].id
            obj[`month${ii + 1}`] = findData[0].monthly
            obj[`outputValue${ii + 1}`] = findData[0].planAmount
          }else{
            obj[`month${ii + 1}`] = i
          }
        })
        return obj
      })
      this.dataSource = dataSource
      console.log( this.dataSource )
      // 如果可编辑的话，没有记录人和记录时间的话，默认上去
      if ((this.form.recorderName ?? '') == '') {
        this.form.recorderName = JSON.parse(sessionStorage.getItem('ycloud-user_info')).name
        this.form.recorderTime = this.getNowDate()
      }
    },
    getOutputYearDetail() {
      this.spinning = true
      getOutputYearDetail({ id: this.yearId })
        .then((res) => {
          this.form = res.data
          this.handlerMonth(res.data.monthVOList)
          this.monthVOListData = res.data.monthVOList;
          this.spinning = false
        })
        .catch(() => {
          this.spinning = false
        })
    },
    submit() {
      const monthVOList = []
      this.dataSource.map((v) => {
        if (v.outputValue1 ?? '' != '') {
          monthVOList.push({
            id: v.id1,
            planAmount: v.outputValue1
          })
        }
        if (v.outputValue2 ?? '' != '') {
          monthVOList.push({
            id: v.id2,
            planAmount: v.outputValue2
          })
        }
        if (v.outputValue3 ?? '' != '') {
          monthVOList.push({
            id: v.id3,
            planAmount: v.outputValue3
          })
        }
      })
      if (monthVOList.length !== this.monthVOListData.length) {  //不能小于返回的值得长度
        return this.$message.warning('年度产值指标填写不完整')
      }
      this.loading = true
      this.setProcessConfig = null
      this.submitApprovalConfirm(4, (flag)=>{
        if(!flag) {
          this.loading = false
          return
        }
        getOutputYearInputYear({
          id: this.yearId,
          yearPlanOutput: this.form.yearPlanOutput,
          monthVOList
        })
                .then((res) => {
                  this.loading = false
                  this.$emit('refreshYearList')
                  this.businessId = res.data
                  this.setProcessConfig = this.processConfig
                  this.visible = false
                })
                .catch(() => {
                  this.loading = false
                })
      })

    },
    onCellChange(key, dataIndex, value) {
      const dataSource = [...this.dataSource]
      const target = dataSource.find((item) => item.key === key)
      if (target) {
        target[dataIndex] = value
        this.dataSource = dataSource
      }
    }
  }
}
</script>
<style lang='less' scoped>
@deep: ~'>>>';
@{deep}.custom-width {
  .ant-form-item-label {
    width: 65px !important;
  }
}
</style>
